package com.zd.lib.listener;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;

import com.zd.lib.App;

import java.util.ArrayList;
import java.util.List;

public class NetWorkChangeListener extends BroadcastReceiver {
    private List<OnNetWorkChangeListener> mList = new ArrayList<OnNetWorkChangeListener>();
    private boolean isAvailable;
    private static NetWorkChangeListener ins;

    private NetWorkChangeListener() {
        IntentFilter mFilter = new IntentFilter();
        mFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
        App.getInstance().registerReceiver(this, mFilter);
    }

    public static NetWorkChangeListener getInstance() {
        if (ins == null) {
            synchronized (NetWorkChangeListener.class) {
                if (ins == null) {
                    ins = new NetWorkChangeListener();
                }
            }
        }
        return ins;
    }

    @Override
    public void onReceive(Context context, Intent intent) {
        if (intent != null && ConnectivityManager.CONNECTIVITY_ACTION.equals(intent.getAction())) {
            ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo info = connectivityManager.getActiveNetworkInfo();
            if (info != null && info.isAvailable()) {
                this.isAvailable = true;
                String name = info.getTypeName();
                for (int i = 0; i < mList.size(); i++) {
                    mList.get(i).onEnable(name);
                }
            } else {
                this.isAvailable = false;
                for (int i = 0; i < mList.size(); i++) {
                    mList.get(i).onDisable();
                }
            }
        }
    }

    public void addChangeListener(OnNetWorkChangeListener l) {
        mList.add(l);
    }

    public void removeChangeListener(OnNetWorkChangeListener l) {
        mList.remove(l);
        if (mList.size() == 0) {
            App.getInstance().unregisterReceiver(this);
            ins = null;
        }
    }

    public boolean isAvailable() {
        return isAvailable;
    }

    public interface OnNetWorkChangeListener {
        void onEnable(String typeName);

        void onDisable();
    }
}
